import request from '@/utils/request'
import { getToken, getServer } from '@/utils/auth'

function requestWorklist() {
  return request({
    url: '/worklist',
    method: 'get'
  })
}

async function requestAttachment(uid) {
  const url = getServer() + '/attachment'
  const resp = await fetch(url, {
    responseType: 'blob',
    headers: {
      'uid': uid,
      'token': getToken()
    }
  })
  return resp.blob()
}

function uploadWorklist(worklist) {
  return request({
    url: '/worklist',
    method: 'post',
    headers: {
      'Content-Type': 'application/json'
    },
    data: JSON.stringify(worklist)
  })
}

function uploadAttachment(fileEntry) {
  return new Promise(
    (resolve, reject) => {
      console.log('[workcard]-[uploadAttachment]-fileEntry: ' + fileEntry.toURL())
      const url = getServer() + '/attachment'
      console.log(url)

      var fileURL = fileEntry.toURL()
      console.log('[workcard]-[uploadAttachment]-fileURL: ' + fileURL)

      var success = function(r) {
        console.log('[workcard]-[uploadAttachment]-Successful upload...')
        console.log('[workcard]-[uploadAttachment]-Code = ' + r.responseCode)
        console.log('[workcard]-[uploadAttachment]-Response Body(uid) = ' + JSON.stringify(r.response))
        resolve(r.response)
      }

      var fail = function(error) {
        console.log('[workcard]-[uploadAttachment]-Error occurred: Code = ' + error.code)
        console.log('[workcard]-[uploadAttachment]-An error has occurred: Body = ' + error.body)
        reject(error)
      }

      // eslint-disable-next-line
      var options = new FileUploadOptions()
      options.fileKey = 'file'
      options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1)
      // options.mimeType = 'image/jpeg'
      options.headers = {
        token: getToken(),
        Connection: 'close'
      }
      options.httpMethod = 'POST'
      options.chunkedMode = false
      console.log('[workcard]-[uploadAttachment]-options:' + JSON.stringify(options))

      // eslint-disable-next-line
      var ft = new FileTransfer()    
      // SERVER must be a URL that can handle the request, like
      // http://some.server.com/upload.php
      ft.upload(fileURL, encodeURI(url), success, fail, options, true)
    }
  )
}

export { requestWorklist, requestAttachment, uploadWorklist, uploadAttachment }
